package com.dn.luckbi.bizmq;

import java.util.Date;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.dn.luckbi.common.ErrorCode;
import com.dn.luckbi.constant.ChartStatusConstant;
import com.dn.luckbi.constant.CommonConstant;
import com.dn.luckbi.exception.BusinessException;
import com.dn.luckbi.manager.AiManager;
import com.dn.luckbi.model.entity.Chart;
import com.dn.luckbi.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author 染染熊
 * @version 1.0
 * @date 2024/3/28 17:28
 */

@Component
@Slf4j
public class MyMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    /**
     * 消费者
     * 监听队列，处理消息
     *
     * @param message
     * @param channel
     * @param deliveryTag
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MyMqConstant.QUEUE),
            exchange = @Exchange(name = MyMqConstant.EXCHANGE, type = ExchangeTypes.DIRECT),
            key = {MyMqConstant.ROUTING_KEY}
    ), ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try {
            if (StrUtil.isBlank(message)) {
                channel.basicNack(deliveryTag, false, false);
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
            }
            // 查询数据
            Chart chart = chartService.getById(message);
            if (ObjectUtil.isEmpty(chart)) {
                channel.basicNack(deliveryTag, false, false);
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图表为空");
            }
            // 修改任务为执行中
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus(ChartStatusConstant.RUNNING);
            boolean updateResult = chartService.updateById(updateChart);
            if (!updateResult) {
                channel.basicNack(deliveryTag, false, false);
                handleChartUpdateError(updateChart.getId(), "更新图表为执行中状态失败");
                return;
            }
            // 调用ai
            String result = aiManager.doChat(CommonConstant.BI_MODEL_ID, buildUserInput(chart));
            // 数据拆分
            String splitSign = "【【【【【";
            String[] split = result.split(splitSign);
            if (split.length < 3) {
                channel.basicNack(deliveryTag, false, false);
                handleChartUpdateError(updateChart.getId(), "Ai 调用失败");
                return;
            }
            String genChart = split[1].trim();
            String genResult = split[2].trim();
            updateChart.setGenChart(genChart);
            updateChart.setGenResult(genResult);
            updateChart.setStatus(ChartStatusConstant.SUCCEED);
            updateResult = chartService.updateById(updateChart);
            if (!updateResult) {
                handleChartUpdateError(updateChart.getId(), "更新图表为成功状态失败");
                return;
            }
            System.out.println("消费者接收到的消息：【" + message + "】");
            // 消息确认
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            handleChartUpdateError(Long.parseLong(message), e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 构建ai分析数据
     *
     * @param chart
     * @return
     */
    public String buildUserInput(Chart chart) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String data = chart.getChartData();
        // 组装ai识别内容
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("分析需求：").append("\n");
        stringBuilder.append(goal)
                .append("，请使用")
                .append(chartType)
                .append("\n");
        stringBuilder.append("原始数据：").append("\n");
        stringBuilder.append(data).append("\n");
        return stringBuilder.toString();
    }


    public void handleChartUpdateError(long chartId, String execMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus(ChartStatusConstant.FAILED);
        chart.setExecMessage(execMessage);
        boolean result = chartService.updateById(chart);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新图表状态失败: " + chartId + "," + execMessage);
        }
    }


}
